package org.base23.video.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.base23.video.domain.dto.*;
import org.base23.video.service.AiGuidanceService;
import org.base23.web.model.Result;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * AI指导控制器
 */
@RestController
@RequestMapping("/ai-guidance")
@Tag(name = "AI运动指导", description = "基于分析结果的智能运动指导对话服务")
@RequiredArgsConstructor
@Slf4j
public class AiGuidanceController {
    
    private final AiGuidanceService aiGuidanceService;
    
    @PostMapping("/conversation")
    @Operation(summary = "创建AI指导会话", description = "为特定分析结果创建新的AI指导会话")
    public Result createConversation(@RequestBody AiGuidanceConversationRequest request) {
        
        log.info("创建AI指导会话，结果ID: {}, 运动类型: {}, 用户ID: {}", 
                request.getResultId(), request.getSportType(), request.getUserId());
        
        try {
            AiGuidanceConversation conversation = aiGuidanceService.createConversation(
                    request.getResultId(), request.getSportType(), request.getUserId());
            
            // 判断是否为新创建的会话
            boolean isNewConversation = conversation.getCreateTime() != null && 
                    conversation.getLastUpdateTime() != null && 
                    conversation.getCreateTime().equals(conversation.getLastUpdateTime());
            
            if (isNewConversation) {
                log.info("成功创建新会话，会话ID: {}", conversation.getConversationId());
            } else {
                log.info("返回已存在的会话，会话ID: {}", conversation.getConversationId());
            }
            
            return Result.data(conversation);
        } catch (Exception e) {
            log.error("创建AI指导会话失败: {}", e.getMessage(), e);
            return Result.fail("创建AI指导会话失败：" + e.getMessage());
        }
    }
    
    @PostMapping("/ask")
    @Operation(summary = "向AI提问", description = "在指定会话中向AI助手提问")
    public Result askQuestion(@RequestBody AiGuidanceRequest request) {
        
        log.info("AI指导提问，会话ID: {}, 问题: {}", request.getConversationId(), request.getQuestion());
        
        try {
            if (request.getQuestion() == null || request.getQuestion().trim().isEmpty()) {
                return Result.fail("问题内容不能为空");
            }
            
            AiGuidanceResponse response = aiGuidanceService.askQuestion(request);
            return Result.data(response);
            
        } catch (Exception e) {
            log.error("AI指导提问失败: {}", e.getMessage(), e);
            return Result.fail("AI指导提问失败：" + e.getMessage());
        }
    }
    
    @GetMapping("/conversation/{conversationId}")
    @Operation(summary = "获取会话历史", description = "获取指定会话的完整对话历史")
    public Result getConversation(@Parameter(description = "会话ID") @PathVariable String conversationId) {
        
        log.info("获取AI指导会话历史，会话ID: {}", conversationId);
        
        try {
            AiGuidanceConversation conversation = aiGuidanceService.getConversation(conversationId);
            if (conversation == null) {
                return Result.fail("会话不存在");
            }
            return Result.data(conversation);
            
        } catch (Exception e) {
            log.error("获取会话历史失败: {}", e.getMessage(), e);
            return Result.fail("获取会话历史失败：" + e.getMessage());
        }
    }
    
    @GetMapping("/conversations")
    @Operation(summary = "获取用户的所有会话", description = "获取指定分析结果下的所有AI指导会话")
    public Result getUserConversations(@Parameter(description = "分析结果ID") @RequestParam String resultId) {
        
        log.info("获取用户AI指导会话列表，结果ID: {}", resultId);
        
        try {
            List<AiGuidanceConversation> conversations = aiGuidanceService.getUserConversations(resultId);
            return Result.data(conversations);
            
        } catch (Exception e) {
            log.error("获取用户会话列表失败: {}", e.getMessage(), e);
            return Result.fail("获取用户会话列表失败：" + e.getMessage());
        }
    }
    
    @GetMapping("/suggestions")
    @Operation(summary = "获取推荐问题", description = "基于分析结果生成推荐问题列表")
    public Result getSuggestedQuestions(
            @Parameter(description = "分析结果ID") @RequestParam String resultId,
            @Parameter(description = "运动类型") @RequestParam String sportType) {
        
        log.info("获取AI指导推荐问题，结果ID: {}, 运动类型: {}", resultId, sportType);
        
        try {
            List<String> suggestions = aiGuidanceService.generateSuggestedQuestions(resultId, sportType);
            return Result.data(suggestions);
            
        } catch (Exception e) {
            log.error("获取推荐问题失败: {}", e.getMessage(), e);
            return Result.fail("获取推荐问题失败：" + e.getMessage());
        }
    }
    
    @PostMapping("/conversation/{conversationId}/end")
    @Operation(summary = "结束会话", description = "标记会话为已完成状态")
    public Result endConversation(@Parameter(description = "会话ID") @PathVariable String conversationId) {
        
        log.info("结束AI指导会话，会话ID: {}", conversationId);
        
        try {
            aiGuidanceService.endConversation(conversationId);
            return Result.data("会话已结束");
            
        } catch (Exception e) {
            log.error("结束会话失败: {}", e.getMessage(), e);
            return Result.fail("结束会话失败：" + e.getMessage());
        }
    }
    
    @PostMapping("/quick-ask")
    @Operation(summary = "快速提问", description = "无需创建会话，直接基于分析结果快速提问")
    public Result quickAsk(
            @Parameter(description = "分析结果ID") @RequestParam String resultId,
            @Parameter(description = "运动类型") @RequestParam String sportType,
            @Parameter(description = "问题内容") @RequestParam String question,
            @Parameter(description = "相关时间戳（可选）") @RequestParam(required = false) Double relatedTimestamp) {
        
        log.info("AI指导快速提问，结果ID: {}, 问题: {}", resultId, question);
        
        try {
            if (question == null || question.trim().isEmpty()) {
                return Result.fail("问题内容不能为空");
            }
            
            AiGuidanceRequest request = new AiGuidanceRequest();
            request.setResultId(resultId);
            request.setSportType(sportType);
            request.setQuestion(question);
            request.setRelatedTimestamp(relatedTimestamp);
            
            AiGuidanceResponse response = aiGuidanceService.askQuestion(request);
            return Result.data(response);
            
        } catch (Exception e) {
            log.error("快速提问失败: {}", e.getMessage(), e);
            return Result.fail("快速提问失败：" + e.getMessage());
        }
    }
} 